import {fileURLToPath, URL} from 'node:url'
import {defineConfig, loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import alias from "@rollup/plugin-alias";
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers'
import vueJsx from '@vitejs/plugin-vue-jsx'
// @ts-ignore
export default ({mode, command}) => {
    const env: Record<string, string> = loadEnv(mode, process.cwd());
    return defineConfig({
        server: {
            host: '0.0.0.0',
            cors: true,
            port: 3000,
            https: false,
            proxy: {
                '/api': {
                    target: env.VITE_APP_BASE_URL,
                    changeOrigin: true,
                    ws: false,
                    rewrite: (path: string) => path.replace(/^\/api/, ""),
                }
            }
        },
        plugins: [
            alias(),
            vue(),
            vueJsx(),
            AutoImport({
                resolvers: [ElementPlusResolver({importStyle:"sass"})],
                imports: ["vue", "vue-router", "pinia"],
                dirs: ["./src/service", "./src/utils"],
                dts: "src/auto-import.d.ts"
            }),
            Components({
                resolvers: [ElementPlusResolver({importStyle:"sass"})],
                dts: "src/components.d.ts"
            }),
        ],
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url))
            }
        },
        build: {
            sourcemap: false,
            minify: 'terser',
            chunkSizeWarningLimit: 1500,
            terserOptions: {
                compress: {
                    drop_console: true,
                    drop_debugger: true
                }
            },
            rollupOptions: {
                output: {
                    manualChunks(id: string) {
                        if (id.includes('node_modules')) {
                            return id
                                .toString()
                                .split('node_modules/')[1]
                                .split('/')[0]
                                .toString();
                        }
                    },
                    chunkFileNames: (chunkInfo) => {
                        const facadeModuleId: string[] = chunkInfo.facadeModuleId
                            ? chunkInfo.facadeModuleId.split('/')
                            : [];
                        const fileName: string =
                            facadeModuleId[facadeModuleId.length - 2] || '[name]';
                        return `js/${fileName}/[name].[hash].js`;
                    }
                }
            }

        },
    })
}
